<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>RRID DEVICE TEST PAGE</title>
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <!-- Fixed Message Area -->
      <div id="fixed-messages" style="position:relative;z-index:9999;"></div>
      <h1 class="text-center">UHF RFID Device Test Page</h1>

          <!-- Device Management Section -->
          <div class="mt-4">
            <h3>Device Management</h3>
    
            <!-- Open Device -->
            <button id="open-device-btn" class="btn btn-success">Open Device</button>
    
            <!-- Close Device -->
            <button id="close-device-btn" class="btn btn-danger">Close Device</button>
    
            <!-- Get Device Info -->
            <button id="device-info-btn" class="btn btn-info">Get Device Info</button>
          </div>


      <!-- Inventory Section -->
      <div class="mt-4">
        <h3>Inventory</h3>
        <button id="inventory-btn" class="btn btn-primary">Perform Inventory</button>
        <button id="inventory-tid-btn" class="btn btn-secondary">Perform Inventory with TID</button>
        <table class="table mt-3" id="inventory-table">
          <thead>
            <tr>
              <th>#</th>
              <th>EPC</th>
              <th>TID</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>

      <!-- Read Tag Section -->
      <div class="mt-4">
        <h3>Read Tag</h3>
        <form id="read-tag-form">
          <div class="mb-3">
            <label for="read-uid" class="form-label">Tag UID (EPC)</label>
            <input type="text" class="form-control" id="read-uid" required>
          </div>
          <div class="mb-3">
            <label for="read-block-start" class="form-label">Block Start</label>
            <input type="number" class="form-control" id="read-block-start" value="0" required>
          </div>
          <div class="mb-3">
            <label for="read-block-count" class="form-label">Block Count</label>
            <input type="number" class="form-control" id="read-block-count" value="1" required>
          </div>
          <div class="mb-3">
            <label for="read-mem-type" class="form-label">Memory Type</label>
            <select class="form-select" id="read-mem-type">
              <option value="0">RESERVED</option>
              <option value="1">EPC</option>
              <option value="2">TID</option>
              <option value="3" selected>USER</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary">Read Tag</button>
        </form>
      </div>

      <!-- Write Tag Section -->
      <div class="mt-4">
        <h3>Write Tag</h3>
        <form id="write-tag-form">
          <div class="mb-3">
            <label for="write-uid" class="form-label">Tag UID (EPC)</label>
            <input type="text" class="form-control" id="write-uid" required>
          </div>
          <div class="mb-3">
            <label for="write-block-start" class="form-label">Block Start</label>
            <input type="number" class="form-control" id="write-block-start" value="0" required>
          </div>
          <div class="mb-3">
            <label for="write-data" class="form-label">Data (Hex)</label>
            <input type="text" class="form-control" id="write-data" required>
          </div>
          <div class="mb-3">
            <label for="write-mem-type" class="form-label">Memory Type</label>
            <select class="form-select" id="write-mem-type">
              <option value="0">RESERVED</option>
              <option value="1">EPC</option>
              <option value="2">TID</option>
              <option value="3" selected>USER</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary">Write Tag</button>
        </form>
      </div>



    </div>

    <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    <script>
      function addFixedMessage(message, type = 'info') {
        const alertId = 'alert-' + Date.now() + Math.floor(Math.random()*1000);
        const alertHtml = `
          <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert" style="margin-top:10px;">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
          </div>
        `;
        $('#fixed-messages').append(alertHtml);
      }
      $(document).ready(function() {
        // Inventory Button Click
        $('#inventory-btn').click(function() {
          $.ajax({
            url: '/inventory',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({}),
            success: function(response) {
              const msg = response.message || (response.error ? 'Inventory failed' : 'Inventory success');
              addFixedMessage(msg, response.error ? 'danger' : 'success');
              if (!response.error) {
                const tableBody = $('#inventory-table tbody');
                tableBody.empty();
                if (response.epcs) {
                  // Regular inventory response
                  response.epcs.forEach((epc, index) => {
                    tableBody.append(`<tr><td>${index + 1}</td><td>${epc}</td><td></td></tr>`);
                  });
                } else if (response.tags) {
                  // TID inventory response
                  response.tags.forEach((tag, index) => {
                    tableBody.append(`<tr><td>${index + 1}</td><td>${tag[0]}</td><td>${tag[1]}</td></tr>`);
                  });
                }
              }
            }
          });
        });

        // TID Inventory Button Click
        $('#inventory-tid-btn').click(function() {
          $.ajax({
            url: '/inventory',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({tid: true}),
            success: function(response) {
              const msg = response.message || (response.error ? 'Inventory with TID failed' : 'Inventory with TID success');
              addFixedMessage(msg, response.error ? 'danger' : 'success');
              if (!response.error) {
                const tableBody = $('#inventory-table tbody');
                tableBody.empty();
                response.tags.forEach((tag, index) => {
                  tableBody.append(`<tr><td>${index + 1}</td><td>${tag[0]}</td><td>${tag[1]}</td></tr>`);
                });
              }
            }
          });
        });

        // Read Tag Form Submit
        $('#read-tag-form').submit(function(event) {
          event.preventDefault();
          const data = {
            uid: $('#read-uid').val(),
            block_start: parseInt($('#read-block-start').val()),
            block_count: parseInt($('#read-block-count').val()),
            mem_type: parseInt($('#read-mem-type').val())
          };
          $.ajax({
            url: '/read-tag',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
              const msg = response.message || (response.error ? 'Read tag failed' : `Tag Data: ${response.data}`);
              addFixedMessage(msg, response.error ? 'danger' : 'success');
            }
          });
        });

        // Write Tag Form Submit
        $('#write-tag-form').submit(function(event) {
          event.preventDefault();
          const data = {
            uid: $('#write-uid').val(),
            block_start: parseInt($('#write-block-start').val()),
            data: $('#write-data').val(),
            mem_type: parseInt($('#write-mem-type').val())
          };
          $.ajax({
            url: '/write-tag',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
              const msg = response.message || (response.error ? 'Write tag failed' : 'Tag written successfully!');
              addFixedMessage(msg, response.error ? 'danger' : 'success');
            }
          });
        });

        // Open Device Button Click
        $('#open-device-btn').click(function() {
          $.post('/open-device', function(response) {
            const msg = response.message || (response.error ? 'Open device failed' : 'Open device success');
            addFixedMessage(msg, response.error ? 'danger' : 'success');
          });
        });

        // Close Device Button Click
        $('#close-device-btn').click(function() {
          $.post('/close-device', function(response) {
            const msg = response.message || (response.error ? 'Close device failed' : 'Close device success');
            addFixedMessage(msg, response.error ? 'danger' : 'success');
          });
        });

        // Get Device Info Button Click
        $('#device-info-btn').click(function() {
          $.post('/device-info', function(response) {
            const msg = response.message || (response.error ? 'Get device info failed' : 'Get device info success');
            addFixedMessage(msg, response.error ? 'danger' : 'info');
          });
        });
      });
    </script>
  </body>
</html>
